package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    @Resource
    private RedisCache redisCache;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 创建用户
     *
     * @param phone   手机号
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {

        // 1 校验手机号
        if (!RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }

        // 2 生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 3 保存验证码
        redisCache.setValue(RedisConstants.LOGIN_CODE_KEY + phone, code,
                RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // 4 发送验证码
        Console.log("发送验证码成功，验证码为：{}", code);

        return Result.ok("验证码发送成功");
    }

    /**
     * 用户登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();

        String sendCode = redisCache.getValue(RedisConstants.LOGIN_CODE_KEY + phone);

        // 1 校验手机号
        if (!RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }

        // 2 校验验证码
        if (ObjectUtil.notEqual(sendCode, code)) {
            return Result.fail("验证码错误");
        }


        // 3 根据手机号查询用户
        User user = lambdaQuery()
                .eq(User::getPhone, phone)
                .last("limit 1")
                .one();

        // 4 判断用户是否存在
        if (user == null) {
            // 4.1 用户不存在，创建新用户
            user = createUserWithPhone(phone);
        }

        // 5 保存用户到redis
        // 5.1 生成token
        String token = IdUtil.simpleUUID();

        // 5.2 将User转换成hash
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        // 5.3 保存到redis
        String key = RedisConstants.LOGIN_USER_KEY + token;
        redisCache.setHash(key, userMap, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);

        redisCache.delete(RedisConstants.LOGIN_CODE_KEY + phone);

        // 5.4 返回token
        return Result.ok(token);
    }

    @Override
    public void logout(HttpServletRequest request) {
        String token = request.getHeader(Constants.AUTHORIZATION);
        redisCache.delete(RedisConstants.LOGIN_USER_KEY + token);
    }

    /**
     * 根据手机号创建用户
     *
     * @param phone 手机号
     * @return
     */
    private User createUserWithPhone(String phone) {
        User user = new User()
                .setPhone(phone)
                .setNickName(DesensitizedUtil.mobilePhone(phone))
                .setPassword(PasswordEncoder.encode("123456"));
        this.save(user);
        return user;
    }
}
